import React, { Component } from 'react';
import StatusBtns from './statusBtns';
import { Balloon, Input, Tag, Message } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import { access } from 'components/accessContainer/util';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import BranchName from '../branch';
import utils from 'utils';
import DraftBtn from '../draftBtn';
import BranchCommitOrder from 'components/branchCommitOrder';
import './index.scss';
import YundouName from 'components/yundouName';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;

const prefix = 'mr-title-info';
export default class Root extends Component {
  constructor(props) {
    super(props);
    this.state = {
      curTitle: props.codeReviewDetail.title || '',
    };
  }

  renderStateBtn = (state) => {
    if (!state) {
      return null;
    }
    if (state === 'merged') {
      return (
        <Tag size="medium">
          <YunxiaoIcon type="merge-line" />
          {intl.get({ id: 'code-assets.components.mrTitleInfo.Merged', defaultMessage: '已合并' })}
        </Tag>
      );
    }
    if (state === 'closed') {
      return (
        <Tag color="red" size="medium">
          <YunxiaoIcon type={'pull-request-closed-line'} />
          {intl.get({
            id: 'code-assets.components.mrTitleInfo.Disabled',
            defaultMessage: '已关闭',
          })}
        </Tag>
      );
    }
    return (
      <Tag color="green" size="medium">
        <YunxiaoIcon type="pull-request-line" />
        {intl.get({ id: 'code-assets.components.mrTitleInfo.Enabled', defaultMessage: '已开启' })}
      </Tag>
    );
  };

  onTitleChange = (value) => {
    this.setState({
      curTitle: value,
    });
  };

  onTitlePressEnter = () => {
    const { curTitle } = this.state;
    if (!curTitle.trim()) {
      Message.error({
        title: intl.get({
          id: 'code-assets.components.mrTitleInfo.TheTitleMustBeSpecified',
          defaultMessage: '标题不能为空',
        }),
      });

      return;
    }
    if (curTitle === this.props.codeReviewDetail.title) {
      return;
    }
    const modifyData = {};
    modifyData.title = curTitle.trim();
    this.props.modifyCr(modifyData, () => {
      Message.success({
        title: intl.get({
          id: 'code-assets.components.mrTitleInfo.TheTitleHasBeenModified',
          defaultMessage: '标题修改成功',
        }),
      });
    });
  };

  render() {
    const { codeReviewDetail, mrTabKey, mr_ahead_behind_info } = this.props;
    const { curTitle } = this.state;
    const { role } = pathResource;
    const author = codeReviewDetail.author || {};
    const curAssignees = codeReviewDetail.assignees
      ? codeReviewDetail.assignees.filter((item) => {
          return item.status === 'approved';
        })
      : [];
    curAssignees.forEach((item) => {
      if (item.avatar_url) item.avatarUrl = item.avatar_url;
    });
    // mr开启状态
    const isMrOpen =
      codeReviewDetail.state &&
      codeReviewDetail.state !== 'merged' &&
      codeReviewDetail.state !== 'closed';
    return (
      <div className={`${prefix}`}>
        <div className={`${prefix}-left`}>
          {this.renderStateBtn(codeReviewDetail.state)}
          <div className={`${prefix}-main`}>
            <div className={`${prefix}-main-info`}>
              <React.Fragment>
                {access(PROJECT_WRITE_ROLES, role) ? (
                  <Balloon.Tooltip
                    trigger={
                      <span className="mr-title-text">
                        <Input
                          className="mr-title-text-input isedit"
                          onPressEnter={this.onTitlePressEnter}
                          onBlur={(e) => {
                            this.onTitlePressEnter(e);
                            // 失去焦点才恢复原有标题
                            if (!curTitle.trim()) {
                              this.setState({
                                curTitle: codeReviewDetail.title,
                              });
                            }
                          }}
                          onChange={this.onTitleChange}
                          value={curTitle}
                        />
                      </span>
                    }
                    align="r"
                    triggerType="hover"
                  >
                    {codeReviewDetail?.title}
                  </Balloon.Tooltip>
                ) : (
                  <span className="mr-title-text">
                    <Input
                      className="mr-title-text-input"
                      defaultValue={codeReviewDetail.title}
                      disabled
                    />
                  </span>
                )}
              </React.Fragment>
            </div>
            <div className={`${prefix}-main-desc`}>
              <div>
                {codeReviewDetail.is_auto_create === true ||
                codeReviewDetail.is_auto_create === 'true' ? (
                  <YundouName />
                ) : (
                  author.name
                )}
                {intl.get({ id: 'code-assets.components.mrTitleInfo.In', defaultMessage: '于' })}
                {utils.getBeautyTime(codeReviewDetail.created_at)}
                {intl.get({
                  id: 'code-assets.components.mrTitleInfo.CreateExpectationsWill',
                  defaultMessage: '创建，期望将',
                })}
                <span className="branch-bg">
                  <BranchName branchType="source_branch" {...this.props} />
                </span>
                {intl.get({
                  id: 'code-assets.components.mrTitleInfo.Merge',
                  defaultMessage: '合并至',
                })}

                <span className="branch-bg">
                  <BranchName branchType="target_branch" {...this.props} />
                </span>
              </div>
              {isMrOpen &&
                mr_ahead_behind_info &&
                (mr_ahead_behind_info.behind || mr_ahead_behind_info.ahead) && (
                  <BranchCommitOrder
                    info={mr_ahead_behind_info}
                    targetBranch={codeReviewDetail.targetBranch || codeReviewDetail.target_branch}
                    style={{ width: 100, marginLeft: 8, height: 20 }}
                  />
                )}
            </div>
          </div>
        </div>
        <div className={`${prefix}-right`}>
          {['overview', '/'].includes(mrTabKey) && curAssignees.length ? (
            <Balloon.Tooltip
              trigger={
                <div className="assignees">
                  <YunxiaoIcon type="member-success-lin" />
                  <span>
                    <span className="num">{curAssignees.length}&nbsp;</span>
                    {intl.get({
                      id: 'code-assets.components.mrTitleInfo.PassedReview',
                      defaultMessage: '人通过评审',
                    })}
                  </span>
                </div>
              }
              align="t"
            >
              {curAssignees.map((item) => item.name).join('、')}
              {intl.get({
                id: 'code-assets.components.mrTitleInfo.Passed',
                defaultMessage: '已通过',
              })}
            </Balloon.Tooltip>
          ) : null}

          <DraftBtn {...this.props} />
          <StatusBtns {...this.props} />
        </div>
      </div>
    );
  }
}
